package Petgoods;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
买家进入过后的控制界面，由商品表product控制，其只有id，名称，数量字段，价格
按1可以查看所有商品的详细信息
按2购买商品使数量减去购买数量，买家金额减去总价格
按3可以查看买家buyer表剩余的金额
按4可以充值金额
 */
public class Buyercontrols {
    public void purchase() {
        Buyermeau buy = new Buyermeau();
        buy.meau();
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        switch (num) {
            case 1:
                viewproduct();
                break;
            case 2:
                purchasegoods();
                break;
            case 3:
                viewbalance();
                break;
            case 4:
                rechargebalance();
                break;
            default:
                System.out.println("无效输入，已退出");
                break;
        }
    }

    private void viewproduct() {
        JdbcUtil util = new JdbcUtil();
        String sql = "SELECT name, number, price FROM product";
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            // 处理结果集
            while (rs.next()) {
                String name = rs.getString("name");
                int number = rs.getInt("number");
                int price = rs.getInt("price");
                System.out.println("商品名称: " + name + ", 数量: " + number + ", 价格: " + price);
            }
            util.closeResource(rs, conn, ps);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void purchasegoods() {
        JdbcUtil util = new JdbcUtil();
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入想要购买商品名字：");
        String productName = sc.nextLine();
        System.out.println("购买的数量");
        int quantity = sc.nextInt();

        Connection conn = null;
        try {
            conn = util.getConn();
            conn.setAutoCommit(false); // 开启事务

            // 步骤1: 获取商品价格
            String getPriceSQL = "SELECT price FROM product WHERE name = ?";
            PreparedStatement psGetPrice = conn.prepareStatement(getPriceSQL);
            psGetPrice.setString(1, productName);
            ResultSet rs = psGetPrice.executeQuery();

            if (!rs.next()) {
                System.out.println("商品不存在！");
                return;
            }

            int unitPrice = rs.getInt("price");
            int totalCost = unitPrice * quantity;

            // 步骤2: 更新商品库存
            String updateProductSQL = "UPDATE product SET number = number - ? WHERE name = ?";
            try (PreparedStatement psUpdateProduct = conn.prepareStatement(updateProductSQL)) {
                psUpdateProduct.setInt(1, quantity);
                psUpdateProduct.setString(2, productName);
                psUpdateProduct.executeUpdate();
            }

            // 步骤3: 更新买家余额
            Scanner scBuyer = new Scanner(System.in);
            System.out.println("请输入买家姓名:");
            String buyerName = scBuyer.nextLine();
            String updateBuyerSQL = "UPDATE buyer SET balance = balance - ? WHERE name = ?";
            try (PreparedStatement psUpdateBuyer = conn.prepareStatement(updateBuyerSQL)) {
                psUpdateBuyer.setInt(1, totalCost);
                psUpdateBuyer.setString(2, buyerName);
                int affectedRows = psUpdateBuyer.executeUpdate();

                if (affectedRows == 0) {
                    conn.rollback();
                    System.out.println("买家不存在或余额不足！");
                    return;
                }
            }

            conn.commit();
            System.out.println("购买成功！");

        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void viewbalance() {
        JdbcUtil util = new JdbcUtil();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查看的姓名");
        String name = sc.nextLine();
        String sql = "SELECT balance FROM buyer WHERE name=?";
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int balance = rs.getInt("balance");
                System.out.println("买家 " + name + " 的余额为: " + balance);
            } else {
                System.out.println("未找到该买家的信息");
            }
            util.closeResource(rs, conn, ps);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void rechargebalance() {

            JdbcUtil util = new JdbcUtil();
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入要充值的姓名");
            String name = sc.nextLine();
            System.out.println("请输入充值金额");
            int num = sc.nextInt();
            String sql = "UPDATE buyer SET balance=balance+? where name=?";
            try {
                Connection conn = util.getConn();
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setInt(1, num);
                ps.setString(2, name);
                int rows = ps.executeUpdate();
                if (rows > 0) {
                    System.out.println("充值成功");
                } else {
                    System.out.println("充值失败，未找到该买家的信息");
                }
                util.closeResource(null, conn, ps);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
}
